package algorithm;

public class EightQueen {
    public static void main(String[] args) {
        int[][] board = new int[8][8];
        //一维
        BHH bhh = new BHH();
        bhh.game(board, 0);
    }
}
class BHH {
    private int res = 0;
    public void game(int[][] board, int row){
        // 一维中 i = board[row]
        for(int i = 0; i < 8; i++){
            if(checkBoard(board, row, i)){
                board[row][i] = 1;
                if(row == 7){
                    end(board, res);
                }else{
                    game(board, row + 1);
                }
                //回溯
                //一维不需要 下一次直接覆盖了
                board[row][i] = 0;
            }
        }
    }
    public boolean checkBoard(int[][] board, int row, int col){
        //同列
        for(int i = 0; i < row; i++){
            if(board[i][col] == 1)
                return false;
        }
        //斜线
        for(int i = 0; i < row; i++){
            for(int j = 0; j < 8; j++){
                if(Math.abs(Math.abs(row - i) - Math.abs(col - j)) < 0.001 && board[i][j] == 1)
                    return false;
            }
        }
        return true;
    }
    public void end(int[][] board, int res){
        this.res = ++res;
        System.out.println("第" + res);
        for (int i = 0; i < 8 ; i++) {
            for (int j = 0; j < 8 ; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.print("\n");
        }
        System.out.println();
    }

}
